# You've been asked to analyse a set of sales data which you can find in sales.csv

# Open the file and read the data
# find the:
#   - largest sale day (highest sale amount)
#   - average sale amount
#   - the widget which has been sold the most
# and print these out in a nice, human-readable format

# for a challenge - add a menu so the user picks which piece of data to show

# Additional hints:
# - Remember to handle file errors
# - The first row contains headers: Date, Product, Sales_Amount, Units_Sold, Region
# - Sales amounts are stored as strings - you'll need to convert to int() for math
# - For finding the highest selling widget, use a dictionary to count units sold per product
# - For average, sum all sales amounts and divide by number of rows
import csv

def load_sales_data(filename):
    """Load sales data from CSV file and return as a list of dictionaries"""
    sales_data = []
    try:
        with open(filename, 'r') as file:
            reader = csv.DictReader(file)  # Uses headers as dictionary keys
            for row in reader:
                # Convert numeric fields to appropriate types
                try:
                    row['Sales_Amount'] = int(row['Sales_Amount'])
                    row['Units_Sold'] = int(row['Units_Sold'])
                    sales_data.append(row)
                except ValueError:
                    print(f"Skipping invalid row: {row} (non-numeric values)")
        return sales_data
    except FileNotFoundError:
        print(f"Error: The file '{filename}' was not found.")
        return None
    except Exception as e:
        print(f"Error reading file: {e}")
        return None

def find_largest_sale_day(sales_data):
    """Find the day with the highest single sale amount"""
    if not sales_data:
        return None
    # Sort by sales amount (descending) and pick first
    largest_sale = max(sales_data, key=lambda x: x['Sales_Amount'])
    return {
        'date': largest_sale['Date'],
        'amount': largest_sale['Sales_Amount'],
        'product': largest_sale['Product']
    }

def calculate_average_sale(sales_data):
    """Calculate average sale amount across all transactions"""
    if not sales_data:
        return None
    total_sales = sum(row['Sales_Amount'] for row in sales_data)
    return total_sales / len(sales_data)

def find_top_widget(sales_data):
    """Find the widget with the most total units sold"""
    if not sales_data:
        return None
    product_units = {}
    # Count total units per product
    for row in sales_data:
        product = row['Product']
        units = row['Units_Sold']
        if product in product_units:
            product_units[product] += units
        else:
            product_units[product] = units
    # Find product with maximum units
    top_product = max(product_units.items(), key=lambda x: x[1])
    return {
        'product': top_product[0],
        'total_units': top_product[1]
    }

def display_menu():
    """Display the user menu"""
    print("\nSales Data Analysis Menu")
    print("1. Show largest sale day")
    print("2. Show average sale amount")
    print("3. Show top-selling widget")
    print("4. Exit")
    return input("Please select an option (1-4): ")

def main():
    # Load data first
    sales_data = load_sales_data('sales.csv')
    if not sales_data:
        return  # Exit if data couldn't be loaded

    # Menu loop
    while True:
        choice = display_menu()
        
        if choice == '1':
            largest_sale = find_largest_sale_day(sales_data)
            if largest_sale:
                print(f"\nLargest sale day: On {largest_sale['date']}, "
                      f"the sale of {largest_sale['product']} reached ${largest_sale['amount']:,}")
        
        elif choice == '2':
            avg_sale = calculate_average_sale(sales_data)
            if avg_sale:
                print(f"\nAverage sale amount: ${avg_sale:,.2f}")
        
        elif choice == '3':
            top_widget = find_top_widget(sales_data)
            if top_widget:
                print(f"\nTop-selling widget: {top_widget['product']} "
                      f"with {top_widget['total_units']:,} units sold")
        
        elif choice == '4':
            print("Exiting program. Goodbye!")
            break
        
        else:
            print("Invalid option. Please enter a number between 1 and 4.")

if __name__ == "__main__":
    main()